<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Files,
  Calendar,
  User,
  House, // 新增 House 图标
  DocumentAdd, // 新增 DocumentAdd 图标
  Star, // 新增 Star 图标
} from "@element-plus/icons-vue";
import { useUserStore } from "../stores/user";
import MessagePopover from "./MessagePopover.vue"; // 引入 MessagePopover 组件
import { logoutUserApi } from "../api/user";
import { getUnreadMessageCountByType } from "../api/message"; // 新增：引入接口

interface NavState {
  activeIndex: string;
  unreadMessages: number;
}

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const state = ref<NavState>({
  activeIndex: "1",
  unreadMessages: 0,
});

// 获取未读消息数
const fetchUnreadMessages = async () => {
  try {
    const userId = userStore.id; // 实际应取当前登录用户id
    const res = await getUnreadMessageCountByType(Number(userId));
    if (res && res.code === 200 && res.data) {
      // 合计所有类型未读消息数
      const {
        postLike = 0,
        comment = 0,
        system = 0,
        resourceLike = 0,
      } = res.data;
      state.value.unreadMessages = postLike + comment + system + resourceLike;
    } else {
      state.value.unreadMessages = 0;
    }
  } catch (error) {
    console.error("获取未读消息失败:", error);
    state.value.unreadMessages = 0;
  }
};

// 搜索功能
const searchQuery = ref("");
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({
      name: "SearchResult",
      query: { keyword: searchQuery.value.trim() },
    });
  }
};

onMounted(() => {
  fetchUnreadMessages();
  // 定时刷新未读消息
  setInterval(fetchUnreadMessages, 60000);
  getActiveIndexByPath(route.path); // 每次挂载时都检查并设置高亮
});

const navigateTo = (path: string) => {
  router.push(path);
};

// 路由与菜单 index 的映射（支持精确和前缀匹配）
const routeToIndexMap: Array<{ path: string; index: string }> = [
  { path: "/forumhome", index: "1" },
  { path: "/resources", index: "5" },
  { path: "/ai-assistant", index: "6" },
  { path: "/schedule", index: "7" },
  { path: "/create-center", index: "creation-center" },
  { path: "/favorites", index: "9" },
  { path: "/profile", index: "8" },
];

// 根据当前路由设置高亮菜单
const getActiveIndexByPath = (path: string) => {
  // 优先精确匹配
  const exact = routeToIndexMap.find((item) => item.path === path);
  if (exact) return exact.index;
  // 再做最长前缀匹配
  let matched = "";
  let matchedIndex = "";
  for (const item of routeToIndexMap) {
    if (
      (path === item.path || path.startsWith(item.path + "/")) &&
      item.path.length > matched.length
    ) {
      matched = item.path;
      matchedIndex = item.index;
    }
  }
  return matchedIndex || "1";
};

watch(
  () => route.path,
  (path) => {
    state.value.activeIndex = getActiveIndexByPath(path);
  },
  { immediate: true }
);

onMounted(() => {
  fetchUnreadMessages();
  setInterval(fetchUnreadMessages, 60000);
  // 移除 activeIndex 的赋值，依赖 watch 自动更新
});

const handleLogout = async () => {
  try {
    const id = userStore.id || localStorage.getItem("userId") || 1;
    await logoutUserApi(id);
  } catch (e) {
    // 可选：错误处理
    console.error("退出登录接口调用失败", e);
  }
  // 使用 store 封装的登出方法
  userStore.logout();
  // 跳转到登录页
  router.push("/login");
};
</script>

<template>
  <div class="navbar">
    <el-menu
      :default-active="state.activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      :ellipsis="false"
    >
      <div class="left-menu-group">
        <el-menu-item
          index="1"
          @click="navigateTo('/forumhome')"
          style="margin-left: 24px"
        >
          <el-icon><House /></el-icon>论坛首页
        </el-menu-item>
        <el-menu-item index="5" @click="navigateTo('/resources')">
          <el-icon><Files /></el-icon>学习资料
        </el-menu-item>
        <el-menu-item index="6" @click="navigateTo('/ai-assistant')">
          <span class="ai-icon" style="display: flex; align-items: center">
            <svg
              t="1750747373559"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="5186"
              width="1em"
              height="1em"
              style="vertical-align: middle"
            >
              <path
                d="M501.824 32C303.552 32 141.504 176.992 141.504 357.76c0 23.712 2.816 47.104 8.32 69.856l-51.008 114.208a32 32 0 0 0 24.704 44.736c54.272 7.744 76.672 31.168 76.672 77.312v111.552a64 64 0 0 0 64 64h20.704a64 64 0 0 1 64 64V960a32 32 0 0 0 32 32h345.6a32 32 0 0 0 0-64h-313.6v-24.608a128 128 0 0 0-128-128h-20.736v-111.552c0-65.664-32.192-110.688-91.2-131.136l39.872-89.28a31.968 31.968 0 0 0 1.568-21.792 233.088 233.088 0 0 1-8.896-63.904c0-143.712 131.936-261.76 296.32-261.76s296.32 118.016 296.32 261.76a32 32 0 0 0 64 0C862.144 176.992 700.064 32 501.824 32zM904 448a32 32 0 0 0-32 32v360a32 32 0 0 0 64 0V480a32 32 0 0 0-32-32z"
                p-id="5187"
              ></path>
              <path
                d="M673.888 466.656c-11.744-25.568-48.416-24.64-58.816 1.536l-132.8 333.76a32 32 0 0 0 59.488 23.68l32.608-81.92c0.576 0.032 1.088 0.32 1.664 0.32h154.848l38.176 83.104a31.968 31.968 0 1 0 58.144-26.72l-153.312-333.76zM599.68 680l47.264-118.72 54.528 118.72H599.68z"
                p-id="5188"
              ></path>
            </svg> </span
          >AI助手
        </el-menu-item>
        <el-menu-item index="7" @click="navigateTo('/schedule')">
          <el-icon><Calendar /></el-icon>课表日程
        </el-menu-item>
      </div>

      <div class="flex-grow" />

      <el-menu-item index="3">
        <el-input
          v-model="searchQuery"
          placeholder="搜索内容..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 1024 1024"
              style="width: 1em; height: 1em; vertical-align: middle"
            >
              <path
                fill="currentColor"
                d="m795.904 750.72 124.992 124.928a32 32 0 0 1-45.248 45.248L750.656 795.904a416 416 0 1 1 45.248-45.248zM480 832a352 352 0 1 0 0-704 352 352 0 0 0 0 704"
              ></path>
            </svg>
          </template>
        </el-input>
      </el-menu-item>

      <!-- 创作中心菜单项 -->
      <el-menu-item
        index="creation-center"
        @click="navigateTo('/create-center')"
      >
        <el-icon><DocumentAdd /></el-icon>创作中心
      </el-menu-item>

      <!-- 消息菜单项移动到搜索和个人中心之间 -->
      <MessagePopover :unread-messages="state.unreadMessages" />

      <!-- 新增收藏夹菜单项，位于消息和个人中心之间 -->
      <el-menu-item index="9" @click="navigateTo('/favorites')">
        <el-icon><Star /></el-icon>收藏夹
      </el-menu-item>

      <!-- 个人中心下拉菜单 -->
      <el-dropdown>
        <span
          class="el-menu-item"
          style="cursor: pointer; display: flex; align-items: center; gap: 4px"
        >
          <el-icon><User /></el-icon>个人中心<el-icon style="margin-left: 2px"
            ><i class="el-icon-arrow-down"></i
          ></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="navigateTo('/profile')"
              >个人中心</el-dropdown-item
            >
            <el-dropdown-item @click="navigateTo('/follow')"
              >关注列表</el-dropdown-item
            >
            <el-dropdown-item divided @click="handleLogout"
              >退出登录</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-menu>
  </div>
</template>

<style scoped>
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  box-shadow: 0 4px 32px rgba(162, 89, 236, 0.08),
    0 1px 6px rgba(162, 89, 236, 0.04);
  border-bottom: 1px solid rgba(162, 89, 236, 0.1);
}

.flex-grow {
  flex-grow: 1;
}

.search-input {
  width: 300px;
  margin: 0 20px;
}

.el-menu-demo {
  padding: 0 24px;
}

.left-menu-group {
  display: flex;
  gap: 8px;
}

:deep(.el-menu--horizontal) {
  border-bottom: none;
  background: transparent;
}

:deep(.el-menu-item) {
  display: flex;
  align-items: center;
  gap: 8px;
  border-radius: var(--radius-md);
  margin: 0 4px;
  padding: 0 16px;
  transition: all 0.3s ease;
  color: var(--text-primary);
  font-weight: 500;
}

:deep(.el-menu-item:hover) {
  background: linear-gradient(
    135deg,
    rgba(162, 89, 236, 0.1) 0%,
    rgba(91, 110, 225, 0.1) 100%
  );
  color: var(--primary-purple);
  transform: translateY(-1px);
}

:deep(.el-menu-item.is-active) {
  background: linear-gradient(
    135deg,
    rgba(162, 89, 236, 0.15) 0%,
    rgba(91, 110, 225, 0.15) 100%
  );
  color: var(--primary-purple);
  font-weight: 600;
}

.el-badge {
  margin-left: 8px;
}

:deep(.el-badge__content) {
  background: var(--gradient-purple);
  border: none;
  font-weight: 600;
  font-size: 11px;
}

.ai-icon {
  width: 20px;
  height: 20px;
  font-size: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 4px;
}

.ai-icon svg {
  width: 20px !important;
  height: 20px !important;
}
</style>

{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }
